package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.*;

public class BootStrap {
    /** 定义监听端口号*/
    private  int port=8080;

    //项目路径
    private String webappsPath="";
    //host : 127.0.0.1  context : demo   wrapper : /lagou
    private Map<String,Map<String,Map<String,HttpServlet>>> hosts = new HashMap<>();

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
    /**minicat启动需要初始化展开得一些操作*/
    public  void  start() throws Exception {
        //加载解析相关的配置
        loadServletByMany();
        //定义一个线程池

        int corePoolSize=10;
        int maximumPoolSize=50;
        long keepAliveTime=100L;
        TimeUnit unit=TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue=new ArrayBlockingQueue<>(50) ;
        ThreadFactory threadFactory=Executors.defaultThreadFactory();
        RejectedExecutionHandler handler =new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler);

        //完成1.0版本 （浏览器请求 localhost：8080,返回固定得字符串回到页面）
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.printf("========>>> minicat start on port:" +port);
      /*  while (true){
            Socket socket = serverSocket.accept();
            //有了socket 接收到请求，
            OutputStream outputStream = socket.getOutputStream();
            String responseText= HttpProtocolUtil.getHttpHeader200("hello minicat".getBytes().length)+"hello minicat";
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/

        /**
         * 完成miniCat2.0
         * 需求,封装request和response对象,返回html静态资源文件
         */

       /* while(true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            response.outputHtml(request.getUrl());
            socket.close();
        }*/

        /***
         * 3.0版本.可以请求动态资源
         */
      /*  while(true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            HttpServlet httpServlet = servletMap.get(request.getUrl());
            if(httpServlet==null){

                response.outputHtml(request.getUrl());
            }else {
                httpServlet.service(request,response);
            }
            socket.close();
        }*/

        /**
         * 多线程改造
         */
       /* while(true){
            Socket socket = serverSocket.accept();
            RequestProcessorr requestProcessorr = new RequestProcessorr(socket,servletMap);
            requestProcessorr.start();
        }*/

        /**
         * 线程池改造多线程
         */
      /*  while(true){
            Socket socket = serverSocket.accept();
            RequestProcessorr requestProcessorr = new RequestProcessorr(socket,servletMap);
            //requestProcessorr.start();
            threadPoolExecutor.execute(requestProcessorr);
        }*/

        /***
         * 5.0 多项目部署
         */
        while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessorrV requestProcessorr = new RequestProcessorrV(socket,hosts,webappsPath);
            threadPoolExecutor.execute(requestProcessorr);
        }

    }
    private Map<String,HttpServlet> servletMap=new HashMap<String,HttpServlet>();
    /**
     * 加载解析web.xml 初始化servlet
     */
  /*  private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read(resourceAsStream);
            Element rootElement = read.getRootElement();
            List<Element> servletNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < servletNodes.size(); i++) {
                Element element = servletNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element)element.selectSingleNode("servlet-name");
                String servletname=servletnameElement.getStringValue();
                //<servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element)element.selectSingleNode("servlet-class");
                String servletclass=servletclassElement.getStringValue();

                //根据servler-name的值找到uel-pattern
                Element servletMapping = (Element)rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletname + "']");
                //  /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                    servletMap.put(urlPattern, (HttpServlet) Class.forName(servletclass).newInstance());

            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }*/

    private void loadServletByMany() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();


        try {
            //解析server.xml
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> portNodes = rootElement.selectNodes("//Connect");
            Element element = (Element) rootElement.selectSingleNode("//Connect");
            port = Integer.parseInt(element.attributeValue("port"));

            List<Element> hostsEle = rootElement.selectNodes("//Host");//获取host

            for (int i = 0; i <hostsEle.size() ; i++) {
                String hostName = hostsEle.get(i).attributeValue("name");

                //项目集
                Map<String,Map<String,HttpServlet>> contexts =new HashMap<>();
                webappsPath = hostsEle.get(i).attributeValue("appBase");//host对应项目路径路径
                webappsPath = webappsPath.replaceAll("\\\\","/");

                File file = new File(webappsPath);
                if(file.exists() && !file.isFile()) {

                    File [] files = file.listFiles();
                    for (int j = 0; j < files.length; j++) {
                        //项目
                        Map<String,HttpServlet> context = new HashMap<>();
                        String webPath = files[j].getPath();//项目路径
                        //单个项目文件名
                        String fileName = webPath.replace(file.getPath()+"\\","");
                        //读取web.xml文件
                        File webXml = new File(webPath+"\\web.xml");
                        InputStream resourceAsStreamWeb = new FileInputStream(webXml);
                        SAXReader saxReaderWeb = new SAXReader();


                        Map<String,HttpServlet> wrapper = new HashMap<String,HttpServlet>();
                        //解析各个项目web.xml
                        try {
                            Document documentWeb = saxReaderWeb.read(resourceAsStreamWeb);
                            Element rootElementWeb = documentWeb.getRootElement();

                            List<Element> selectNodes = rootElementWeb.selectNodes("//servlet");
                            for (int k = 0; k < selectNodes.size(); k++) {


                                Element elementWeb =  selectNodes.get(k);
                                // <servlet-name>lagou</servlet-name>
                                Element servletnameElement = (Element) elementWeb.selectSingleNode("servlet-name");
                                String servletName = servletnameElement.getStringValue();
                                // <servlet-class>server.LagouServlet</servlet-class>
                                Element servletclassElement = (Element) elementWeb.selectSingleNode("servlet-class");

                                String servletClass = servletclassElement.getStringValue();//class绝对路径
                                // 根据servlet-name的值找到url-pattern
                                Element servletMapping = (Element) rootElementWeb.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                                // /lagou
                                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                                String pakageDir = webPath.replaceAll("\\\\","/");
                                MyClassLoader loader = new MyClassLoader(pakageDir+"/");
                                Class<?> clazz  = loader.findClass(servletClass);
                                wrapper.put(urlPattern, (HttpServlet) clazz.getClassLoader().loadClass(servletClass).newInstance());
                            }

                        } catch (DocumentException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }



                        //context.put(fileName,);
                        contexts.put(fileName,wrapper);
                    }


                }

                if("localhost".equalsIgnoreCase(hostName)){
                    hosts.put("127.0.0.1",contexts);//增加127.0.0.1 对应 localhost
                }
                hosts.put(hostName,contexts);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }



        /*       */

    }

    /**
     * Minicat得启动入口
     */

    public static void main(String[] args) {
        BootStrap bootStrap = new BootStrap();
        try {
            bootStrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
